package com.uum.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.uum.blog.pojo.entity.Comment;
import com.uum.blog.pojo.entity.CommentLike;
import com.uum.blog.service.CommentLikeService;
import com.uum.blog.service.CommentService;
import com.uum.common.core.result.Result;
import com.uum.web.util.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Tsang_yc
 * @since 2022-02-10
 */
@Api(tags = "评论点赞接口")
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/like")
public class CommentLikeController {

    private final CommentLikeService commentLikeService;
    private final CommentService commentService;

    @ApiOperation("点赞")
    @PostMapping("add")
    public Result addLike (@RequestBody CommentLike commentLike) {
        commentLikeService.addLike(commentLike);
        return Result.success();
    }

    @ApiOperation("点灭")
    @PostMapping("delete")
    @Transactional
    public Result deleteLike (@RequestBody CommentLike commentLike) {
        Long commentId = commentLike.getCommentId();
        Long userId = JwtUtils.getUserId();
        Long like = commentLikeService.deleteLike(commentId, userId);
        if (like == 0) {//缓存中无数据
            //在数据库中删除点赞信息
            commentLikeService.remove(new LambdaQueryWrapper<CommentLike>().eq(CommentLike::getCommentId, commentId).eq(CommentLike::getUserId, userId));
            //查出该评论的点赞数量
            Integer likeCount = commentLikeService.count(new LambdaQueryWrapper<CommentLike>().eq(CommentLike::getCommentId, commentId));
            //更新评论点赞数量信息
            commentService.update(new LambdaUpdateWrapper<Comment>().set(Comment::getLikeCount, likeCount).eq(Comment::getCommentId, commentId));
        }
        return Result.success();
    }

}

